<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model :model="form" slot="detail" :rules="rules" ref="dynamicValidateForm">
        <a-row :gutter="24">
          <a-col :span="24">
            <a-form-model-item
              label="日期"
              :labelCol="{ span: 3 }"
              :wrapperCol="{ span: 18 }"
              style="margin: 0 0 15px 20px"
              prop="priceDate"
              :rules="{
                required: true,
                message: '请选择日期',
                trigger: 'change',
              }"
            >
              <a-date-picker
                :disabled="isShow" 
                format="YYYY-MM-DD"
                placeholder="请选择日期"
                v-model="form.priceDate"
                @change="onChange"
                style="width: 100%"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <div v-for="(item, index) in form.details" :key="index" class="">
          <a-row>
            <a-col :span="11">
              <a-form-model-item
                style="margin-bottom: 20px"
                label="区块"
                :labelCol="{ span: 8 }"
                :wrapperCol="{ span: 16 }"
                :prop="'details.' + index + '.blockName'"
                :rules="{
                  required: true,
                  message: '请输入区块名称',
                  trigger: 'blur',
                }"
              >
                <a-input :disabled="isShow" :maxLength="10" placeholder="请输入区块名称" v-model="item.blockName" />
              </a-form-model-item>
            </a-col>
            <a-col :span="11" v-if="!isShow">
              <a-form-model-item :labelCol="{ span: 0 }" :wrapperCol="{ span: 14 }">
                <a-icon
                  type="minus-circle"
                  style="font-size: 16px; color: #d93026; margin-top: 10px; margin-left: 370px"
                  @click="delItem(form.details, c)"
                ></a-icon>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <div v-for="(v, indexs) in item.items" :key="indexs">
              <a-col :span="11">
                <a-form-model-item
                  style="margin-bottom: 20px"
                  :label="`${v.variety}(元/斤)`"
                  :labelCol="{ span: 8 }"
                  :wrapperCol="{ span: 16 }"
                >
                  <a-input-number :min="0" :precision="1" :disabled="isShow" placeholder="请输入价格" v-model="v.price" style="width: 100%" />
                </a-form-model-item>
              </a-col>
            </div>
          </a-row>
        </div>
        <a-row>
          <a-col :span="24">
            <a-button
              type="dashed"
              style="width: 260px; margin: 10px 0 0 128px"
              icon="plus"
              @click="addDomain"
              v-if="!isShow"
            >
              添加区块
            </a-button>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import pick from 'lodash.pick'
import JFormContainer from '@/components/jeecg/JFormContainer'
import JDictSelectTag from '@/components/dict/JDictSelectTag'
import JMultiSelectTag from '@/components/dict/JMultiSelectTag'
import moment from 'moment'
import JDate from '@/components/jeecg/JDate'
export default {
  name: 'EveryDayPriceMsgForm',
  components: {
    JFormContainer,
    JDictSelectTag,
    JMultiSelectTag,
    JDate,
  },
  props: {
    //流程表单data
    formData: {
      type: Object,
      default: () => {},
      required: false,
    },
    //表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false,
    },
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    //详情
    isShow: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  data() {
    return {
      id: '',
      getResult: {},
      oldYear: '',
      isAdd: true,
      varietyOptions: [],
      needsDetail: [],
      open: false,
      result: {},
      form: {
        priceDate: undefined,
        details: [
          {
            blockName: undefined,
            items: this.needsDetail,
          },
        ],
      },
      model: {},
      labelCol: {
        xs: { span: 3 },
        sm: { span: 2 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 10 },
      },
      confirmLoading: false,
      rules: {},
      url: {
        add: '/system/tqppOfferPrice/add',
        edit: '/system/tqppOfferPrice/edit',
        queryById: '/system/tqppOfferPrice/queryById',
      },
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    },
  },
  created() {
    //如果是流程中表单，则需要加载流程表单data
    this.showFlowData()
  },
  mounted() {
    this.getVarietyList().then(() => {
      this.varietyOptions.map((j) => {
        let obj = {}
        obj.price = undefined
        obj.varietiesId = j.value
        obj.variety = j.text
        this.needsDetail.push(obj)
      })
    })
  },
  methods: {
    onChange(val) {
      this.form.priceDate = moment(val).format('YYYY-MM-DD')
    },
    async getVarietyList() {
      const res = await getAction('/sys/dict/getDictItems/txpp_tree_varieties,name,id')
      if (res.success) {
        this.varietyOptions = res.result
      } else {
        this.$message.error(res.message)
      }
    },
     handlePlantNumCheck(rule,value,callback){
        if (!value || new RegExp(/^\d+(\.\d{1,2})?$/).test(value)){
          callback();
        }else{
          callback("最多保留一位小数!");
        }
      },
    addDomain() {
      const arr = []
      this.varietyOptions.map((j) => {
        let obj = {}
        obj.price = ''
        obj.varietiesId = j.value
        obj.variety = j.text
        arr.push(obj)
      })
      this.form.details.push({
        blockName: undefined,
        items: arr,
      })
    },
    delItem(items, index) {
      this.$confirm({
        title: '提示',
        content: '确定删除该条数据吗 ?',
        onOk() {
          items.splice(index, 1)
        },
        onCancel() {},
      })
    },
    add() {
      this.isAdd = true
      this.edit({})
    },
    edit(record) {
      this.$nextTick(() => {
        setTimeout(() => {
        this.$refs.dynamicValidateForm.resetFields()
        },0);
      })
      if (!record.id) {
        this.form.priceDate = undefined
        this.form.details = []
      } else {
        this.id = record.id
        let params = { id: record.id }
        getAction(this.url.queryById, params).then((res) => {
          if (res.success) {
            this.form.priceDate = res.result.priceDate
            const details = []
            res.result.detailsList.map((i) => {
              const it = {}
              it.blockName = i.blockName
              let keys = Object.keys(i.items)
              const arr = []
              this.varietyOptions.map((j) => {
                let obj = {}
                obj.price = undefined
                obj.varietiesId = j.value
                obj.variety = j.text
                arr.push(obj)
              })
              keys &&
                keys.length &&
                keys.map((v) => {
                  arr.map((a, index) => {
                    if (a.varietiesId === v) {
                      arr[index].price = i.items[v]
                    }
                  })
                })
              it.items = arr
              details.push(it)
            })
            this.form.details = details
          }
        })
        this.isAdd = false
      }
      this.visible = true
    },
    //渲染流程表单数据
    showFlowData() {
      if (this.formBpm === true) {
        let params = { id: this.formData.id }
        getAction(this.url.queryById, params).then((res) => {
          if (res.success) {
            this.edit(res.result, false)
          }
        })
      }
    },
    submitForm() {
      const that = this
      // 触发表单验证
      this.$refs.dynamicValidateForm.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          this.$emit('loading', that.confirmLoading)
          let httpurl = ''
          let method = ''
          const formCopy = JSON.parse(JSON.stringify(this.form))
          formCopy.details.map((i) => {
            const a = []
            i.items.map((k, index) => {
              if (k.price) {
                a.push(k)
              }
            })
            i.items = a
          })
          let formData = formCopy
          let noData = []
          formData.details.map((item) => {
            if (item.items.length === 0) {
              noData.push(item)
            }
          })
          if (noData.length) {
            this.$message.warning('添加的每个区块请至少维护一个品种的价格')
            this.confirmLoading = false
            this.$emit('loading', that.confirmLoading)
            return
          } else {
            if (this.isAdd) {
              httpurl += this.url.add
              method = 'post'
            } else {
              httpurl += this.url.edit
              method = 'PUT'
              formData.id = this.id
            }
            httpAction(httpurl, formData, method)
              .then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.$emit('ok')
                } else {
                  that.$message.warning(res.message)
                }
              })
              .finally(() => {
                that.confirmLoading = false
                this.$emit('loading', that.confirmLoading)
              })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    popupCallback(row) {
      this.form.setFieldsValue(pick(row, 'year', 'details'))
    },
  },
}
</script>
<style lang="less" scoped>
.ant-calendar-picker {
  width: 250.44px;
}
/deep/.varietyForm {
  .ant-table-tbody > tr::hover {
    background: transparent !important;
  }
  .ant-table-tbody > tr > td {
    border-bottom: none;
  }
  .ant-table-tbody .ant-table-row td {
    padding-top: 5px !important;
    padding-bottom: 5px !important;
  }
  .ant-table-thead {
    display: none;
  }
}
.ant-checkbox-wrapper {
  margin: 10px 0;
}
.ant-radio-group {
  padding: 0 10px;
}
.ant-form-item-control {
  line-height: 0px !important;
}
.ant-col-sm-5 {
  width: 100px;
}
.projectstyle {
  .ant-col-sm-16 {
    width: 88%;
    .ant-form-item-control {
      .ant-form-item-children {
        > div {
          width: 95% !important;
        }
      }
    }
  }
}
</style>